

package com.sixfoot.adminsys.frames.userPerm;

import com.sixfoot.adminsys.DemoProperties;
import com.sixfoot.adminsys.utilities.UIUtils;
import com.sixfoot.domain.Permission;
import com.sixfoot.domain.Role;
import com.sixfoot.facade.permission.PermissionDto;
import com.sixfoot.facade.role.RoleDto;
import com.sixfoot.facade.user.UserDto;
import com.sixfoot.facade.user.UserInputArgs;
import com.sixfoot.service.RoleService;
import com.sixfoot.service.UserService;
import org.dozer.DozerBeanMapper;
import org.dozer.Mapper;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import java.util.List;


@DemoProperties(
        value = "用户权限",
        category = "权限管理",
        description = "进入可以设置用户权限"
)
public class UserPerm extends JPanel {

    private static final Dimension VGAP10 = new Dimension(1, 10);

    private RoleService roleService = (RoleService) UIUtils.getBean("roleService");
    private UserService userService = (UserService) UIUtils.getBean("userService");

    private JList userList; // 用户JLIST
    private JTree noHasRoleTree; // 未拥有角色树
    private JTree hasRoleTree; // 已拥有角色树
    private JButton addPermBtn;
    private JButton removePermBtn;
    private DefaultTreeModel noHasRoleTreeModel;
    private DefaultTreeModel hasRoleTreeModel;
    private final ActionListener addPermActionListener = new AddPermActionListener();
    private final ActionListener removePermActionListener = new RemovePermActionListener();
    private DefaultListModel<UserDto> userModalList = new DefaultListModel<>();

    private JScrollPane selectScrollPane = new JScrollPane();
    private JScrollPane selectedScrollPane = new JScrollPane();

    public static void main(String[] args) {
        JFrame frame = new JFrame(UserPerm.class.getAnnotation(DemoProperties.class).value());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new UserPerm());
        frame.setPreferredSize(new Dimension(800, 600));
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public UserPerm() {
        List<UserDto> users = getUsers();
        userModalList = new DefaultListModel<UserDto>();
        for (UserDto u : users) {
            userModalList.addElement(u);
        }
        setLayout(new BorderLayout());
        JPanel centerPanel = new JPanel();
        centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.X_AXIS));
        add(centerPanel, BorderLayout.CENTER);

        JPanel userPanel = new JPanel();
        userPanel.setLayout(new BoxLayout(userPanel, BoxLayout.Y_AXIS));
        userPanel.add(Box.createRigidArea(VGAP10));
        userPanel.add(new JLabel("用户"));
        userPanel.add(Box.createRigidArea(VGAP10));
        userList = new JList(userModalList);
        userList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane userScrollPane = new JScrollPane(userList);
        userPanel.add(userScrollPane);

        JPanel selectPanel = new JPanel();
        selectPanel.setLayout(new BoxLayout(selectPanel, BoxLayout.Y_AXIS));
        selectPanel.add(Box.createRigidArea(VGAP10));
        selectPanel.add(new JLabel("未拥有角色"));
        selectPanel.add(Box.createRigidArea(VGAP10));
        selectScrollPane = new JScrollPane(noHasRoleTree);
        selectPanel.add(selectScrollPane);

        JPanel selectedPanel = new JPanel();
        selectedPanel.setLayout(new BoxLayout(selectedPanel, BoxLayout.Y_AXIS));
        selectedPanel.add(Box.createRigidArea(VGAP10));
        selectedPanel.add(new JLabel("已拥有角色"));
        selectedPanel.add(Box.createRigidArea(VGAP10));
        selectedScrollPane = new JScrollPane(hasRoleTree);
        selectedPanel.add(selectedScrollPane);

        addPermBtn = new JButton(">>");
        addPermBtn.addActionListener(addPermActionListener);
        removePermBtn = new JButton("<<");
        removePermBtn.addActionListener(removePermActionListener);
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS));
        buttonPanel.add(addPermBtn);
        buttonPanel.add(Box.createRigidArea (new Dimension(1, 15)));
        buttonPanel.add(removePermBtn);
        buttonPanel.setAlignmentY(Component.TOP_ALIGNMENT );
        buttonPanel.setBorder(BorderFactory.createEmptyBorder (15, 5, 15, 5));
        centerPanel.add(Box.createRigidArea (new Dimension(15, 15)));
        centerPanel.add(userPanel);
        centerPanel.add(Box.createRigidArea (new Dimension(100, 100)));
        centerPanel.add(selectPanel);
        centerPanel.add(buttonPanel);
        centerPanel.add(selectedPanel);
        centerPanel.add(Box.createRigidArea (new Dimension(15, 15)));

        userList.addListSelectionListener(lsl);
        userList.setSelectedIndex(0);
    }

    public List<UserDto> getUsers() {
        List<UserDto> users = userService.findAll();
        return users;
    }

    // 角色选择监听
    private ListSelectionListener lsl = new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            if (e.getValueIsAdjusting()) {
                return;
            }
            DefaultMutableTreeNode hasRoleTreeRoot = new DefaultMutableTreeNode("1");
            DefaultMutableTreeNode noHasRoleTreeRoot = new DefaultMutableTreeNode("2");

            List<String> roleIds = new ArrayList<>();
            List<RoleDto> allRole = roleService.findAll();
            UserDto user = (UserDto) userList.getSelectedValue();
            Set<Role> roles = user.getRoles();
            if (roles != null) {
                Iterator<Role> iterator = roles.iterator();
                while (iterator.hasNext()) {
                    roleIds.add(iterator.next().getId());
                }
            }
            for (RoleDto r : allRole) {
                if (roleIds.contains(r.getId())) {
                    DefaultMutableTreeNode node = new DefaultMutableTreeNode(r);
                    if (r.getPerms() != null) {
                        for (Permission p : r.getPerms()) {
                            node.add(new DefaultMutableTreeNode(p));
                        }
                    }
                    hasRoleTreeRoot.add(node);
                } else {
                    DefaultMutableTreeNode node = new DefaultMutableTreeNode(r);
                    if (r.getPerms() != null) {
                        for (Permission p : r.getPerms()) {
                            node.add(new DefaultMutableTreeNode(p));
                        }
                    }
                    noHasRoleTreeRoot.add(node);
                }
            }
            noHasRoleTree = new JTree(noHasRoleTreeRoot);
            noHasRoleTree.setRootVisible(false);
            hasRoleTree = new JTree(hasRoleTreeRoot);
            hasRoleTree.setRootVisible(false);
            selectedScrollPane.setViewportView(hasRoleTree);
            selectScrollPane.setViewportView(noHasRoleTree);
            noHasRoleTreeModel = (DefaultTreeModel) noHasRoleTree.getModel();
            hasRoleTreeModel = (DefaultTreeModel) hasRoleTree.getModel();
        }
    };

    // 监听增加权限按钮点击
    private class AddPermActionListener implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            if (noHasRoleTree.getLastSelectedPathComponent() == null) {
                return;
            }
            TreePath[] selectionPaths = noHasRoleTree.getSelectionPaths();
            DefaultMutableTreeNode hasRoleTreeRoot = (DefaultMutableTreeNode) hasRoleTreeModel.getRoot();
            DefaultMutableTreeNode noHasRoleTreeRoot = (DefaultMutableTreeNode) noHasRoleTreeModel.getRoot();
            for (int i = 0; i < selectionPaths.length; i++) {
                DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) selectionPaths[i].getLastPathComponent();
                if (selectedNode != null && selectedNode.getParent() != null) {
                    //删除指定节点
                    noHasRoleTreeModel.removeNodeFromParent(selectedNode);
                    RoleDto role = (RoleDto) selectedNode.getUserObject();
                }
                hasRoleTreeModel.insertNodeInto(selectedNode, hasRoleTreeRoot, hasRoleTreeRoot.getChildCount());
            }
            hasRoleTree = new JTree(hasRoleTreeRoot);
            hasRoleTree.setRootVisible(false);
            selectedScrollPane.setViewportView(hasRoleTree);
            noHasRoleTree = new JTree(noHasRoleTreeRoot);
            noHasRoleTree.setRootVisible(false);
            selectScrollPane.setViewportView(noHasRoleTree);

            Mapper mapper = new DozerBeanMapper();
            List<String> selectedRoleIds = new ArrayList<>();
            Set<Role> roles = new HashSet<>();
            for (int i = 0; i < hasRoleTreeRoot.getChildCount(); i++) {
                DefaultMutableTreeNode child = (DefaultMutableTreeNode) hasRoleTreeRoot.getChildAt(i);
                RoleDto role = (RoleDto) child.getUserObject();
                selectedRoleIds.add(role.getId());
                roles.add(mapper.map(role, Role.class));
            }
            UserDto selectedUser = getSelectedUser();
            UserInputArgs userInputArgs = new UserInputArgs();
            userInputArgs.setId(selectedUser.getId());
            userInputArgs.setLocked(selectedUser.getLocked());
            userInputArgs.setPassword(selectedUser.getPassword());
            userInputArgs.setUsername(selectedUser.getUsername());
            userInputArgs.setRoleIds(selectedRoleIds);
            userService.update(userInputArgs);
            selectedUser.setRoles(roles);
        }
    }

    // 监听移除权限按钮点击
    private class RemovePermActionListener implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            if (hasRoleTree.getLastSelectedPathComponent() == null) {
                return;
            }
            TreePath[] selectionPaths = hasRoleTree.getSelectionPaths();
            DefaultMutableTreeNode hasRoleTreeRoot = (DefaultMutableTreeNode) hasRoleTreeModel.getRoot();
            DefaultMutableTreeNode noHasRoleTreeRoot = (DefaultMutableTreeNode) noHasRoleTreeModel.getRoot();
            for (int i = 0; i < selectionPaths.length; i++) {
                DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) selectionPaths[i].getLastPathComponent();
                if (selectedNode != null && selectedNode.getParent() != null) {
                    //删除指定节点
                    hasRoleTreeModel.removeNodeFromParent(selectedNode);
                }
                noHasRoleTreeModel.insertNodeInto(selectedNode, noHasRoleTreeRoot, noHasRoleTreeRoot.getChildCount());
            }
            noHasRoleTree= new JTree(noHasRoleTreeRoot);
            noHasRoleTree.setRootVisible(false);
            selectScrollPane.setViewportView(noHasRoleTree);
            hasRoleTree= new JTree(hasRoleTreeRoot);
            hasRoleTree.setRootVisible(false);
            selectedScrollPane.setViewportView(hasRoleTree);

            Mapper mapper = new DozerBeanMapper();
            List<String> selectedRoleIds = new ArrayList<>();
            Set<Role> roles = new HashSet<>();
            for (int i = 0; i < hasRoleTreeRoot.getChildCount(); i++) {
                DefaultMutableTreeNode child = (DefaultMutableTreeNode) hasRoleTreeRoot.getChildAt(i);
                RoleDto role = (RoleDto) child.getUserObject();
                selectedRoleIds.add(role.getId());
                roles.add(mapper.map(role, Role.class));
            }
            UserDto selectedUser = getSelectedUser();
            UserInputArgs userInputArgs = new UserInputArgs();
            userInputArgs.setId(selectedUser.getId());
            userInputArgs.setLocked(selectedUser.getLocked());
            userInputArgs.setPassword(selectedUser.getPassword());
            userInputArgs.setUsername(selectedUser.getUsername());
            userInputArgs.setRoleIds(selectedRoleIds);
            userService.update(userInputArgs);
            selectedUser.setRoles(roles);
        }
    }

    // 获取当前被选中的角色
    private UserDto getSelectedUser() {
        return (UserDto) userList.getSelectedValue();
    }

    // 获取想要增加的权限
    private List<PermissionDto> getSelectedAddPerms() {
        return null;
    }


}
